-- UIDesertAltar
-- Created by zouyb Sep/25/2015
-- 沙漠祭坛

require "game/ui/form/dungeon/special/UIGenieLamp"

UIDesertAltar = class("UIDesertAltar", function()
    return cc.Layer:create();
end);

function UIDesertAltar.create(gridData)
    return UIDesertAltar.new(gridData);
end

-- 不同灯油道具ID
local ALTAR_MATERIALS = { 7168, 7169, 7179, };

-- 按钮数量
local BTN_COUNT = 4;

-- 构造函数
function UIDesertAltar:ctor(gridData)
    self:setName("UIDesertAltar");

    self.gridData  = gridData;

    -- 是否有神灯
    local requireItemId = DungeonM.query(self.gridData.class, "dbase").require_item;
    self.hasLamp = (ItemM.getAmount(ME.user, requireItemId) > 0) or EquipM.isEquiped(requireItemId);

    -- 是否有圣灯油
    local saintOilId = DungeonM.query(self.gridData.class, "dbase").saint_oil_item;
    self.hasSaintOil = ItemM.getAmount(ME.user, saintOilId) > 0;

    local csbPath = "layout/dungeon/BuildingView.csb";
    if self.hasLamp then
        csbPath = "layout/dungeon/special/DesertAltar.csb";
    end

    local node = cc.CSLoader:createNode(csbPath);
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 1);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 适配
function UIDesertAltar:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 注册事件处理回调函数
function UIDesertAltar:registerEventCallback()
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            cclog("UIDesertAltar 界面析构清理");
        elseif eventType == "enter" then
        end
    end);
end

-- 注册点击事件
function UIDesertAltar:registerTouchEvent()
    -- 注册返回按钮点击事件
    local node = self.node;
    local btnBack = findChildByName(node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIDesertAltar");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));
    if not self.hasLamp then
        btnBack:setVisible(false);
    end

    -- 按钮标题
    local buttonNames = { "btn_ok" };
    local buttonTitles = { getLocStr("btn_text_leave") };
    if self.hasLamp then
        buttonNames = { "btn1", "btn2", "btn3" };
        buttonTitles = { getLocStr("btn_text_rub"), getLocStr("btn_text_rub"), getLocStr("btn_text_rub") };
    end

    -- 注册按钮点击事件
    self.buttons = {};
    for i = 1, #buttonNames do
        local btn = findChildByName(node, "CT/"..buttonNames[i]);
        local function onOkClick(sender, eventType)
            if eventType == ccui.TouchEventType.ended then
                if not self.hasLamp then
                    AudioM.playFx("button_return");
                    -- 关闭当前界面
                    UIMgr.getCurrentScene():removeFormByName("UIDesertAltar");
                    return;
                end

                AudioM.playFx("button_select");

                local ret, itemId = DesertAltarM.canSubmit(i);
                local itemName = ItemM.query(itemId, "name");
                if ret == false then
                    local msg = string.format(getLocStr("something_not_enough"), itemName);
                    alert(msg);
                    return;
                end

                -- 提示成功细信息
                local msg = string.format(getLocStr("fill_oil_success"), itemName);
                alert(msg);

                -- 神灯巨人出现, 弹出对话框
                self:showLampGenie(i, itemId);
            end
        end
        AddTouchEventListener(btn, onOkClick);
        TextStyleM.setTextStyle(btn, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
        btn:setTitleText(buttonTitles[i]);

        table.insert(self.buttons, btn);
    end
end

-- 神灯巨人出现, 弹出对话框
function UIDesertAltar:showLampGenie(option, itemId)
    -- 显示神灯巨人 出现动画、音效
    local effectNode = findChildByName(self.node, "CT/effect_node");
    AudioM.playFx("aladin");
    playEffect(effectNode, 1254, 0, 10);

    -- 禁止多次点击
    for _, btn in pairs(self.buttons) do
        setButtonEnabled(btn, false);
    end

    -- 禁止点击返回键
    local btnBack = findChildByName(self.node, "BT/btn_back");
    setButtonEnabled(btnBack, false);

    local function delay()
        -- 神灯显示
        local function callback()
            self:showGenieOnGrid()

            -- 打开神灯界面
            local uiForm = UIGenieLamp.create(option, self.gridData, itemId);
            UIMgr.getCurrentScene():addForm(uiForm);

            self:setVisible(false);
        end

        -- 格子上显示神灯巨人待机动画
        self:showGenie(callback);
    end
    performWithDelay(self, delay, 0.1);
end

-- UI上显示神灯巨人待机动画
function UIDesertAltar:showGenie(callback)
    -- 界面上图标隐藏
    local ct = findChildByName(self.node, "CT");
    local iconImg    = findChildByName(self.node, "CT/icon");
    iconImg:setVisible(false);

    local effectAnim = createEffectAnim(1253);

    -- 显示神灯待机
    local effectNode = findChildByName(self.node, "CT/effect_node");
    effectAnim:setPosition(0, -50);
    effectNode:addChild(effectAnim);
    effectAnim:play(1, 30, false, 0.5, callback);
end

-- 神灯动画显示在格子上
function UIDesertAltar:showGenieOnGrid()
    local uiDungeon = UIDungeonMgr.getCurLevel();

    -- 先隐藏建筑图标
    local pos = self.gridData:getPos();
    local uiGrid = uiDungeon:getAllGrids()[pos];
    uiGrid.item:setVisible(false);

    -- 创建神灯动画
    uiGrid.effectAnim = createEffectAnim(1253);

    -- 获取effect根节点
    local effectParentNode = uiDungeon:getEffectParent();
    local worldPos = uiGrid:convertToWorldSpace(cc.p(0, 0));
    local targetPos = uiGrid:getParent():convertToNodeSpace(worldPos);

    -- 播放待机
    uiGrid.effectAnim:play(1, 70, true, 0.5);
    uiGrid.effectAnim:setPosition(targetPos);
    uiGrid.effectAnim:setScale(uiGrid.effectAnim:getScale() * 0.88);
    effectParentNode:addChild(uiGrid.effectAnim);
end

-- 重绘
function UIDesertAltar:redraw()
    -- 查询建筑配置
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    local descLabel  = findChildByName(self.node, "CT/desc");
    local iconImg    = findChildByName(self.node, "CT/icon");
    local titleLabel = findChildByName(self.node, "CT/title_node/title");
    local kerning, kerning2 = 0, 0;
    if getLang() ~= "zh" then
        kerning, kerning2 = -3, -1;
    end

    titleLabel:setString(buildingInfo["title"]);
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);
    iconImg:loadTexture(iconPath);
    local iconSize = iconImg:getContentSize();

    iconImg:setScale(1.3);

    TextStyleM.setTextStyle(titleLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning);
    convertTextToArtWord(titleLabel, "images/ui/text_mask/text_mask2.png");
    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN, false, kerning2);

    -- 有没有神灯，描述显示不一样
    local desc;
    if not self.hasLamp then
        desc = getLocStr("desert_altar_desc1");
    else
        desc = string.format(getLocStr("desert_altar_desc2"), self:getNeedAmount());
    end

    applyString(descLabel, desc);

    -- 消耗物品
    if self.hasLamp then
        self:redrawOilCost();
    end
end

function UIDesertAltar:getNeedAmount()
    local cost = DesertAltarM.calcSubmitCost(1);
    for classId, amount in pairs(cost) do
        return amount;
    end

    return 0;
end

-- 重绘消耗
function UIDesertAltar:redrawOilCost()
    local costPart = findChildByName(self.node, "CT/cost_part");

    for i, id in pairs(ALTAR_MATERIALS) do
        local child = findChildByName(costPart, "cost_node" .. i);

        -- 显示材料图标
        local iconImg = findChildByName(child, "icon");
        local iconPath = getItemIconPath(ItemM.query(id, "icon"));
        iconImg:loadTexture(iconPath);
        iconImg:setPositionY(10);

        -- 显示数量信息
        local amountLabel = findChildByName(child, "amount");
        local needAmount = self:getNeedAmount();
        local curAmount = ItemM.getAmount(ME.user, id);

        -- 消耗不足时，显示红色
        if curAmount < needAmount then
            TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_RED, false);
            setButtonEnabled(self.buttons[i], false);
        else
            TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BEIGE, false);
            setButtonEnabled(self.buttons[i], true);
        end

        if needAmount <= 0 then
            -- 无需消耗
            amountLabel:setString(curAmount .. "/-");
        else

            amountLabel:setString(curAmount .. "/" .. needAmount);
        end
    end
end




